package com.example.im.ws;


import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.example.im.R;
import com.google.gson.Gson;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;

public class HelloActivity extends AppCompatActivity {
    public static final int MSG_HEART = 0x123;
    public static final int MSG_INTERVAL = 3000;
    private WebSocket webSocket;
    public static final String URL = "ws://192.168.0.110:7890/websocket";
    private TextView msgView;
    private List<String> sessionIds = new ArrayList<>();
    Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (MSG_HEART == msg.what) {
                MsgData msgData = new MsgData();
                msgData.setType(MsgType.HEART_BEAT);
                webSocket.send(new Gson().toJson(msgData));
                msgView.append(getNowDate() + ":发送消息 heart beat\n");

                mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_HEART), MSG_INTERVAL);
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        msgView = findViewById(R.id.tv_msg);

        findViewById(R.id.btn_scan).setOnClickListener(v -> {
            scanQRCode();
        });
        findViewById(R.id.btn_update).setOnClickListener(v -> {
            MsgData msgData = new MsgData();
            msgData.setType(MsgType.UPDATE);
            webSocket.send(new Gson().toJson(msgData));
        });
    }

    @Override
    protected void onDestroy() {
        mHandler.removeCallbacksAndMessages(null);
        super.onDestroy();
    }

    private void scanQRCode() {
        IntentIntegrator integrator = new IntentIntegrator(this);
        integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE);
        integrator.setPrompt("提示");
        integrator.setCameraId(0);  // 使用后置摄像头
        integrator.setBeepEnabled(false);
        integrator.setBarcodeImageEnabled(true);
        integrator.initiateScan();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (result != null && !TextUtils.isEmpty(result.getContents())) {
            String sessionId = result.getContents();
            if (sessionIds.contains(sessionId)) {
                return;
            }
            sessionIds.add(sessionId);
            //start
            if (null == webSocket) {
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder().url(URL).build();
                webSocket = client.newWebSocket(request, new MyWebSocketListener());
            } else {
                //这样可以实现扫多个pc端. 同时与多个pc端通信
                MsgData msgData = new MsgData();
                msgData.setSessionId(sessionId);
                msgData.setType(MsgType.REQ);
                msgData.setFileId("123");
                webSocket.send(new Gson().toJson(msgData));
            }

        }
        super.onActivityResult(requestCode, resultCode, data);
    }


    private String getNowDate() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
                Locale.getDefault());
        return simpleDateFormat.format(new java.util.Date());
    }

    private class MyWebSocketListener extends WebSocketListener {
        @Override
        public void onOpen(WebSocket webSocket, okhttp3.Response response) {
            // 连接成功
            msgView.append(getNowDate() + ":连接成功\n");
            MsgData msgData = new MsgData();
            msgData.setSessionId(sessionIds.get(sessionIds.size() - 1));
            msgData.setType(MsgType.REQ);
            msgData.setFileId("123");
            webSocket.send(new Gson().toJson(msgData));
            mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_HEART), MSG_INTERVAL);
        }

        @Override
        public void onMessage(WebSocket webSocket, String text) {
            msgView.append(getNowDate() + ":接受消息" + text + "\n");
            mHandler.removeMessages(MSG_HEART);
            mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_HEART), MSG_INTERVAL);
        }

        @Override
        public void onFailure(WebSocket webSocket, Throwable t, okhttp3.Response response) {
            // 连接失败
            msgView.append(getNowDate() + ":失败" + t.getMessage() + "\n");
        }
    }
}